package com.virecog.utils;

import java.math.BigInteger;

import processing.core.PImage;

public class Utils {

	public static void saveImage(PImage img, String filename) {
		img.save(filename);
	}

	/**
	 * char to byte array
	 * 
	 * @param ch
	 * @return
	 */
	public static byte[] charToBytes(char ch) {
		String str = Character.toString(ch);
		byte[] bytes = str.getBytes();
		return bytes;
	}

	/**
	 * 
	 * @param values
	 * @return
	 */
	public static double[] intArrayToDoubleArray(int[] values) {
		double[] doub = new double[values.length];

		for (int i = 0; i < values.length; i++) {
			doub[i] = values[i];
		}
		return doub;
	}

	public static int[] doubleArrayToIntArray(double[] values) {
		int[] in = new int[values.length];

		for (int i = 0; i < values.length; i++) {
			in[i] = (int) Math.round(values[i]);
		}
		return in;
	}

	/**
	 * byte array to bit array
	 * 
	 * @param bytes
	 * @return
	 */
	public static int[] bytesToBitArray(byte[] bytes) {
		int bits[] = new int[16];

		BigInteger in = new BigInteger(bytes);
		String bitstr = in.toString(2);

		int len = bitstr.length();
		for (int i = 0; i < len; i++) {
			bits[16 - len + i] = Integer.valueOf(String.valueOf(bitstr
					.charAt(i)));
		}

		if (bitstr.length() < 16) {
			for (int i = 0; i < 16 - len; i++) {
				bits[i] = 0;
			}
		}
		return bits;
	}

	/**
	 * char to bit array
	 * 
	 * @param c
	 * @return
	 */
	public static double[] charToBitarray(char c) {
		byte[] bytes = charToBytes(c);
		return intArrayToDoubleArray(bytesToBitArray(bytes));
	}

	/**
	 * 
	 * @param bits
	 * @return
	 */
	public static String intArrayToString(int[] bits) {
		char chars[] = new char[bits.length];
		for (int i = 0; i < bits.length; i++) {
			chars[i] = Character.forDigit(bits[i], 10);
		}
		return new String(chars);
	}

	/**
	 * 
	 * @param bits
	 * @return
	 */
	public static char bitArrayToChar(double[] bits) {

		String str = intArrayToString(Utils.doubleArrayToIntArray(bits));
		BigInteger in = new BigInteger(str, 2);
		byte[] bytes = in.toByteArray();
		str = new String(bytes);
		return str.charAt(0);
	}
}
